package edu.cibertec.action;

import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.sqlmap.client.SqlMapSession;

public class RedireccionandoAction extends Action {
	SqlMapClient sqlMap;
	
	public ActionForward execute ( ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
		
    	try {
    		String resource = "SqlMapConfigApplication.xml";
    		Reader reader = Resources.getResourceAsReader (resource);
    		sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
    	} catch (Exception e) {
    		e.printStackTrace();
    		throw new RuntimeException ("Error cargando configuracion en RedireccionandoAction Cause: " + e);
    	}
    	
		String forwardName = "failure";
		String parametro = request.getParameter("method");
		
		if ( parametro.equals("registroProcesos")) {
			forwardName = listaProcesos(request);
		}
		if ( parametro.equals("listaUsuarios")) {
			forwardName = listaUsuarios(request);
		}
		if ( parametro.equals("cargarArchivos")) {
			forwardName ="lol";
		}
		if ( parametro.equals("listaShoppingCart")) {
			forwardName = "shoppingCart";
		}
		if ( parametro.equals("spIN")) {
			forwardName = "f5";
		}
		if ( parametro.equals("spOUT")) {
			forwardName = "f5";
		}
		if ( parametro.equals("spINOUT")) {
			forwardName = "f5";
		}
		if ( parametro.equals("trx")) {
			forwardName = ejecuta_Trx_Local(request);
		}
		if ( parametro.equals("trxCustom")) {
			forwardName = ejecuta_Trx_Custom(request);
		}
		if ( parametro.equals("mantenerIndicador")) {
			forwardName = "mantenerIndicador";
		}

		return mapping.findForward(forwardName);
	}
	
	
	private String listaProcesos(HttpServletRequest request) throws SQLException {
	List listaProcesos = sqlMap.queryForList("getAllProcesos");
    	
    	if ( listaProcesos.size() > 0 ) {
    		System.out.println("**");
            HttpSession session = request.getSession();
            session.setAttribute("listaProceso",listaProcesos);
        	return "prueba";
        } else {
        	return "failure";
        }
	}
        
	private String listaUsuarios(HttpServletRequest request) throws SQLException {
		
   	    List listaUsuarios = sqlMap.queryForList("getAllUsuarios");
    	
    	if ( listaUsuarios.size() > 0 ) {
    		System.out.println("*listaUsuarios*");
            HttpSession session = request.getSession();
            session.setAttribute("listaUsuario",listaUsuarios);
        	return "f2";
        } else {
        	return "failure";
        }
	}
	


	private String ejecuta_Trx_Local(HttpServletRequest request) throws SQLException {
	
		sqlMap.startTransaction();
		try {
			Map m = new HashMap();
			for (int i = 100; i < 200; i++) {
				m.put("p1", new Integer(i).toString() );
				m.put("p2", new Integer(i).toString().substring(2) );
				sqlMap.insert("insertData", m);
			}
			sqlMap.update("actualizaData");
			
			sqlMap.commitTransaction();
		} finally {
			sqlMap.endTransaction();
		}

		return "f6";
	}

	private String ejecuta_Trx_Custom(HttpServletRequest request) throws SQLException {

		Context ic;
		DataSource ds;
		Connection conn = null;
		SqlMapSession session = null;
		
		try {
			ic = new InitialContext();
			ds =  (DataSource)ic.lookup("java:/comp/env/jdbc/daw2mysql");
			conn = ds.getConnection();
			
			conn.setAutoCommit(false);
			
			session = sqlMap.openSession();

			Map m = new HashMap();
			for (int i = 100; i < 200; i++) {
				m.put("p1", new Integer(i).toString() );
				m.put("p2", new Integer(i).toString().substring(2) );
				session.insert("insertData", m);
			}
			session.update("actualizaData");
			conn.commit();
			
		} catch (Exception e) {
			System.out.println("Error en ejecuta_Trx_Custom " + e.getLocalizedMessage() );
			e.printStackTrace();
			
		} finally {
			if ( session != null ) session.close();
			if ( conn != null ) conn.close();
		}
		
		return "f6";
	}
	
}
